package com.zysc.processflow.common.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 正元智慧城市_
 * @Date: 2022/04/11/15:23
 * @Description:
 */
public class HttpClientUtil {
    public static String get(String url, String name, String idCard){

        String result = null;
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClient.getHttpClient();
        // 参数
        StringBuilder params = new StringBuilder();
        try {
            // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("xm=").append(URLEncoder.encode(name, "utf-8")).append("&").append("zjhm=").append(idCard);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 创建Get请求
        HttpGet httpGet = new HttpGet(url + "?" + params);
        httpGet.setHeader("Apikey","943161936546103296");
//        System.out.println("URL : " + url + "?" + params);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
//            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                result = EntityUtils.toString(responseEntity);
//                System.out.println("响应内容为:" + result);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
//            try {
//                // 释放资源
//                if (httpClient != null) {
//                    httpClient.close();
//                }
//                if (response != null) {
//                    response.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
        return result;
    }

    // 请求参数为json
    public static String post(String url, JSONObject params, Map<String, String> headerMap) throws Exception {
        //目前HttpClient最新版的实现类为CloseableHttpClient
        CloseableHttpClient client = HttpClient.getHttpClient();
        CloseableHttpResponse response = null;
        StringEntity entity=null;
        try {
            //建立Request的对象，一般用目标url来构造，Request一般配置addHeader、setEntity、setConfig
            HttpPost req = new HttpPost(url);
            entity = new StringEntity(params.toString(), "UTF-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            //setHeader,添加头文件
            if(headerMap != null){
                headerMap.forEach((key, value) -> {
                    req.setHeader(key, value);
                });
            }
            req.setHeader("Content-Type", "application/json");
//            req.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //setConfig,添加配置,如设置请求超时时间,连接超时时间
            RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
            req.setConfig(reqConfig);
            //setEntity,添加内容
            req.setEntity(entity);
            //执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
            //其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator（String）取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
            response = client.execute(req);
            HttpEntity responseEntity =  response.getEntity();
            //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
            String result= EntityUtils.toString(responseEntity, "UTF-8");

            if(response.getStatusLine().getStatusCode()==200){
                return result;
            }else{
                return null;
            }
        } catch(Exception e) {
            throw new Exception();
        }finally{
            //一定要记得把entity fully consume掉，否则连接池中的connection就会一直处于占用状态
            EntityUtils.consume(entity);
        }
    }

}
